package com.TechMahindra.wx.controller;

import com.TechMahindra.wx.common.QywxPropertieKeys;
import com.TechMahindra.wx.entity.response.UserInfoResponse;
import com.TechMahindra.wx.utils.PropertiesUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.TechMahindra.wx.utils.HttpClientUtil;
import com.TechMahindra.wx.service.impl.AccessTokenService;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author weican
 */
@RestController
public class LoginController {
	private static Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private HttpServletRequest request;
	
	@RequestMapping("/login")
	public ModelAndView login(){
		ModelAndView mav = new ModelAndView();
		String code = request.getParameter("code");
		log.info("code === " + code);
		String accessToken = AccessTokenService.getAccessToken(PropertiesUtil.getValue(QywxPropertieKeys.approvalTest_secret));

		//获取用户UserId
		String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s", accessToken, code);
		String result = HttpClientUtil.getInstance().sendHttpGet(url);

		log.info("url == " + url);
		log.info("result === " + result);
		UserInfoResponse uir = JSON.parseObject(result, UserInfoResponse.class);
		if (uir.getErrcode() == 0)
			mav.setViewName("redirect:/index.html?userId=" + uir.getUserId());
		else
			mav.setViewName("redirect:/error.html?msg=code:" + uir.getErrcode() + ",errormsg:" + uir.getErrmsg());
		return mav;
	}
}
